#include "analyzer.h"

#include <QJsonDocument>
#include <QMetaProperty>

QVariantMap Analyzer::analyzer(const QObject *object)
{
    QVariantMap childrenMap;

    QObjectList childrens = object->children();
    for (int var = 0; var < childrens.length(); ++var)
    {

        const QObject *children = childrens.at(var);

        QString key = QString("%1:%2").arg(var).arg(children->metaObject()->className());

        childrenMap.insert(key, analyzer(children));
    }

    return childrenMap;
}

QString Analyzer::analyzerJson(const QObject *object)
{
    QVariantMap childrenMap = Analyzer::analyzer(object);
    return QJsonDocument::fromVariant(childrenMap).toJson();
}


#define MAX_DEPTH 15  // 根据实际需求调整

QVariantMap Analyzer::analyzer2(const QObject* object, int depth, QSet<const QObject*>& visited)
{
    QVariantMap node;
    if (!object || depth > MAX_DEPTH || visited.contains(object)) return node;
    visited.insert(object);

    // 基础信息
    node["address"] = QString("0x%1").arg(reinterpret_cast<quintptr>(object), 0, 16);
    node["className"] = object->metaObject()->className();
    node["objectName"] = object->objectName();

    // 属性信息
    QVariantMap properties;
    const QMetaObject* meta = object->metaObject();
    for (int i = 0; i < meta->propertyCount(); ++i) {
        QMetaProperty prop = meta->property(i);
        properties[prop.name()] = object->property(prop.name());
    }
    // 动态属性
    foreach(const QByteArray& dynProp, object->dynamicPropertyNames()) {
        properties[dynProp] = object->property(dynProp);
    }
//    node["properties"] = properties;

    // 递归子对象（改为数组结构）
    QVariantList children;
    foreach(const QObject* child, object->children()) {
        children.append(analyzer2(child, depth + 1, visited));
    }
    if (!children.isEmpty())
    node["son(child)"] = children;

    return node;
}

QString Analyzer::analyzerJson2(const QObject* object)
{
    QSet<const QObject*> visited;
    QVariantMap root = analyzer2(object, 0, visited);
    return QJsonDocument::fromVariant(root).toJson();
}
